import axios from 'axios';
import { get } from 'lodash-es';
import { defineStore } from 'pinia';
import { useAutoAction, useAutoGetter } from './autoActionGetter.js';
import { getStoreId } from './utils.js';

const id = getStoreId('WeatherStore');
export const useWeatherStore = defineStore(id, {
  state: () => ({
    weather: { text: '', temp: '' },
  }),
  getters: {
    getWeather: useAutoGetter({
      getter: (state) => () => state.weather,
      action: function (params) {
        this.getWeatherAsync(params);
      },
    }),
  },
  actions: {
    getWeatherAsync: useAutoAction({
      action: async function (lng, lat) {
        const lngLat = lng + ',' + lat;
        const res = await axios({
          method: 'get',
          url: 'https://devapi.qweather.com/v7/weather/now?key=f3baad3f80b34c3084a079f460d57060&location=' + lngLat,
        }).catch(() => ({}));
        return (this.weather = {
          text: get(res, 'data.now.text'),
          temp: get(res, 'data.now.temp'),
        });
      },
    }),
  },
});
